package ca.cbc.medialib.service;

import ca.cbc.medialib.util.HibernateUtil;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.DatabaseSequenceFilter;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.FilteredDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.filter.ITableFilter;
import org.dbunit.dataset.xml.FlatDtdDataSet;
import org.dbunit.dataset.xml.FlatXmlWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: arash
 * Date: 11-06-27
 * Time: 12:28 PM
 * To add data to the unitDB dataset. Add the data to the database and then run this class. This will extract all the data from database to the dataset.xml file.
 */
public class DatabaseExport {

    public static void main(String[] args) {
        HibernateUtil.getSession().beginTransaction();
        IDatabaseConnection conn = null;
        try {
            conn = new DatabaseConnection(HibernateUtil.getSession().connection());
            ITableFilter filter = new DatabaseSequenceFilter(conn);
            IDataSet dataset = new FilteredDataSet(filter, conn.createDataSet());
            FlatDtdDataSet.write(conn.createDataSet(), new FileOutputStream("src/test/resources/dataset.dtd"));
            FlatXmlWriter datasetWriter = new FlatXmlWriter(new FileOutputStream("src/test/resources/dataset.xml"));
            datasetWriter.setDocType("src/test/resources/dataset.dtd");
            datasetWriter.write(conn.createDataSet());
//            FlatXmlDataSet.write(dataset, new FileOutputStream(new File("src/test/resources/dataset.xml")));
        } catch (DatabaseUnitException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


    }
}
